<template>
    <el-dialog v-model="lowCodeStore.createModelDialog.visible" title="创建模型" width="60%" :draggable="true"
        @close="handleClose(ruleFormRef)">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="model-ruleForm"
            status-icon label-position="top">
            <el-form-item label="名称" prop="name" :rules="[
                {
                    required: true,
                    message: '请输入表名',
                    trigger: 'blur',
                },
            ]">
                <el-input v-model="ruleForm.name" />
            </el-form-item>
            <el-form-item label="描述" prop="comment" :rules="[
                {
                    required: true,
                    message: '请输入描述文字',
                    trigger: 'blur',
                },
            ]">
                <el-input v-model="ruleForm.comment" type="textarea" />
            </el-form-item>
            <el-form-item label="字段" required style="margin-bottom: 0"></el-form-item>
            <el-form-item class="fields-container">
                <el-form-item style="width: 100%; margin-bottom: 5px">
                    <el-col :span="1">序号</el-col><el-col :span="6">显示名称</el-col><el-col :span="1"></el-col><el-col
                        :span="6">字段名</el-col><el-col :span="1"></el-col><el-col :span="4">字段类型</el-col><el-col
                        :span="1"></el-col><el-col :span="3">长度/精度</el-col><el-col :span="1"
                        style="text-align: right">操作</el-col>
                </el-form-item>
                <el-form-item required v-for="(field, index) in ruleForm.fieldList" :key="field.key"
                    style="width: 100%; margin-bottom: 10px">
                    <el-col :span="1">{{ index + 1 }}</el-col>
                    <el-col :span="6">
                        <el-form-item :prop="'fieldList.' + index + '.comment'" :rules="[
                            {
                                required: true,
                                message: '请输入显示名',
                                trigger: 'blur',
                            },
                        ]">
                            <el-input v-model="field.comment" placeholder="显示名" minlength="1" maxlength="36" show-word-limit clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="1"></el-col>
                    <el-col class="text-center" :span="6">
                        <el-form-item :prop="'fieldList.' + index + '.name'" :rules="[
                            {
                                required: true,
                                message: '请输入字段名',
                                trigger: 'blur',
                            },
                        ]">
                            <el-input v-model="field.name" placeholder="字段名" minlength="2" maxlength="36" show-word-limit clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="1"></el-col>
                    <el-col :span="4">
                        <el-form-item :prop="'fieldList.' + index + '.type'" :rules="[
                            {
                                required: true,
                                message: '请选择类型',
                                trigger: 'change',
                            },
                        ]">
                            <el-select v-model="field.type" placeholder="字段类型">
                                <el-option label="CHAR" value="CHAR" />
                                <el-option label="VARCHAR" value="VARCHAR" />
                                <el-option label="INTEGER" value="INTEGER" />
                                <el-option label="DECIMAL" value="DECIMAL" />
                                <el-option label="DATE" value="DATE" />
                                <el-option label="DATETIME" value="DATETIME" />
                                <el-option label="TEXT" value="TEXT" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="1"></el-col>
                    <el-col :span="3">
                        <el-form-item :prop="'fieldList.' + index + '.length'" :rules="[
                            {
                                required: true,
                                message: `请输入${field.type === 'CHAR' ? '长度' : '精度'}`,
                                trigger: 'blur',
                            },
                        ]" v-if="field.type === 'CHAR' || field.type === 'DECIMAL'">
                            <el-input v-model="field.length" :placeholder='field.type === "CHAR" ? "长度" : "精度"' />
                        </el-form-item>
                    </el-col>
                    <el-col :span="1"><svg class="icon" aria-hidden="true" @click.prevent="removeField(field)"
                            style="float: right; cursor: pointer">
                            <use xlink:href="#icon-minus_full"></use>
                        </svg></el-col>
                </el-form-item>
                <el-form-item style="width: 100%;">
                    <el-col :span="1"></el-col>
                    <el-col :span="23" style="display: flex; align-items: center;">
                        <svg class="icon" aria-hidden="true" @click.prevent="addField"
                            style="float: right; cursor: pointer">
                            <use xlink:href="#icon-xinzeng"></use>
                        </svg>
                        <el-button type="primary" link @click="addField">新增</el-button>
                    </el-col>
                </el-form-item>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="resetForm(ruleFormRef)" size="small">重置</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)" size="small">提交</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive } from "vue";
import axios from "axios";
import pinia from "@/store/pinia";
import { useStore } from "@/store/lowCode.js";
const lowCodeStore = useStore(pinia);

const ruleFormRef = ref();
const ruleForm = reactive({
    name: "",
    comment: "",
    fieldList: [
        {
            key: 1,
            comment: "",
            name: "",
            type: "",
            length: null
        },
    ],
});

const removeField = (item) => {
    const index = ruleForm.fieldList.indexOf(item);
    if (index !== -1) {
        ruleForm.fieldList.splice(index, 1);
    }
};

const addField = () => {
    ruleForm.fieldList.push({
        key: ruleForm.fieldList.length + 1,
        comment: "",
        name: "",
        type: "",
    });
};

const submitFormAjax = async () => {
    let submitFormRes = await axios
        .post("/lowcode/module/module/form", {
            "name": ruleForm["name"],
            "comment": ruleForm["comment"],
            "fieldList": ruleForm["fieldList"]
        })
        .then((submitFormRes) => [null, submitFormRes])
        .catch((err) => [err, null]);

    console.log("预览：");
    console.log(submitFormRes);

    if (!submitFormRes[1]) {
        console.log(submitFormRes[1].data.message);
        ElMessage({
            message: submitFormRes[1].data.message,
            type: "error",
        });
        return false;
    }

    submitFormRes = submitFormRes[1];
    console.log(submitFormRes.data.data);

    lowCodeStore.createModelDialog.visible = false;
}

const submitForm = async (formEl) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log("ruleForm!");
            console.log(ruleForm);
            submitFormAjax();
        } else {
            console.log("error submit!", fields);
        }
    });
};

const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
};

const handleClose = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();

    ruleForm.fieldList = [
        {
            key: 1,
            comment: "",
            name: "",
            type: "",
        },
    ]

    lowCodeStore.createModelDialog.visible = false;
};
</script>

<style lang="less" scoped>
.fields-container {
    background: rgb(245, 246, 247);
    padding: 10px 20px;
}

.fields-container /deep/ .el-input__wrapper {
    background-color: rgb(255, 255, 255) !important;
    box-shadow: none !important;
}

.fields-container /deep/ .el-select__wrapper {
    box-shadow: none !important;
}

.model-ruleForm /deep/ .el-form-item__error {
    left: auto !important;
    right: 5px !important;
    top: 70% !important;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>
